MAP_PROJ = new OpenLayers.Projection("EPSG:900913"); // spherical mercator
DATA_PROJ = new OpenLayers.Projection("EPSG:4326"); // WGS84 LatLon

// Convert DATA_PROJ (i.e. WGS84) to MAP_PROJ (i.e. spherical mercator)
function lonlat (lon, lat) {
    return new OpenLayers.LonLat(lon, lat).transform(DATA_PROJ, MAP_PROJ);
}

/* Note about finding features by ID:
   Features are not assigned their KML ids as their feature IDs, unfortunately.
   However, features can be found by any attribute. Simply do 
   mapOverlay.getFeatureBy('fid', id) to retrieve the feature with KML id
   id (i.e. <Placemark id='...'>).

   the file Parking_lots_modified has ids of 42 and 43 assigned to two polygons,
   for testing.
*/

$('document').ready( function () {
    olmap = new OpenLayers.Map('ol-map', {projection: MAP_PROJ});
    // sphericalMercator allows us to draw a vector layer over a map
    gLayer = new OpenLayers.Layer.Google(
	'Google Streets', 
	{
	    sphericalMercator: true,
	    numZoomLevels: 20
	}
    );
    olmap.addLayer(gLayer);
    olmap.setBaseLayer(gLayer);

    // This is the zoom level for OSM
    olmap.setCenter(lonlat(-122.1284, 37.3612), 16);
    //olmap.setCenter(lonlat(-122.1284, 37.3612), 14);
    
    mapOverlay = new OpenLayers.Layer.Vector('Buildings', {
	strategies: [new OpenLayers.Strategy.Fixed()], // Fetch once, no bbox &c
	projection: DATA_PROJ,
	protocol: new OpenLayers.Protocol.HTTP({
	    // It must be on the same web server, or we run into problems with
	    // the HTTP Same-Origin Policy, because OpenLayers uses an
	    // XMLHttpRequest internally.
	    // In fact, some browsers (Chrome) don't even allow you to use it
	    // locally (e.g. file://), you must use a web server. You can use
	    // serveThisDir.py, which I put in SVN, to serve the current dir
	    // on port 3689
	    url: '../../../rooms.kml',
	    format: new OpenLayers.Format.KML({
		extractStyles: true,
		extractAttributes: true
	    })
	})
    });
    olmap.addLayer(mapOverlay);
});

// Check for duplicate names
function checkDuplicates () {
    console.log('Checking for duplicates on layer');
    var names = []; // Store each name in hear so we can check for duplicates
    var duplicates = {}; // Store duplicates here, for generating report
    var duplicatesMap = []; // Store the names of duplicates, so we can iterate
    // over them (iterating over an object is a bad idea)
    mapOverlay.features.forEach( function (feat) {
	console.log('checking feature ' + feat.attributes.name);
	// No array.contains method, so use this standard hack
	if (names.indexOf(feat.attributes.name) == -1) {
	    // This name is not a duplicate
	    names.push(feat.attributes.name);
	}
	else {
	    console.log("It's a duplicate!");
	    // It's a duplicate
	    // Check if it's already been flagged as such
	    if (feat.attributes.name in duplicates) {
		duplicates[feat.attributes.name] += 1; //Increment the counter
	    }
	    else {
		console.log('First report');
		// Flag it as a duplicate
		duplicates[feat.attributes.name] = 2; // It has two refs so far
		duplicatesMap.push(feat.attributes.name);
	    }
	}
    });

    // Generate the report
    var report = 'Duplicates: <br/>';
    // Loop over the map; don't use for (var i in duplicates) - it's
    // inefficient and prone to error
    duplicatesMap.forEach( function (dupl) {
	report += 'Feature <b>' + dupl + '</b> has ' + duplicates[dupl] + ' polygons<br/>';
    });

    // And print the report
    $('#report').innerHTML = report;
    return report;
}